const axios = require("axios");
const { db } = require("../db");
const { getRedisValue, setRedisValue } = require("../db/redis");
const cos = require("../service/tencos");
const { imgUrl, resultsWithCamelCase } = require("../utils/common");
const { getWXUserInfo2 } = require("../routerHandler/wechat");
const { getWXUserInfoByCode } = require('./serviceHelper/wechatHelper');
const { getUserById } = require('../db/usermodel');
const moment = require('moment-timezone');

exports.wallpapers = async (req, res) => {
  const countSql = `select count(*) as count from wallpapers where downloadImageUrl like '%.jpg%' or downloadImageUrl like '%.JPG%' or 
  downloadImageUrl like '%.png%' or downloadImageUrl like '%.PNG%'`;
  const totalCount = await new Promise((resolve, reject) => {
    db.query(countSql, [], (err, results) => {
      if (err) {
        return res.send({
          flag: 500,
          msg: err.message,
        });
      } else {
        resolve(results[0].count);
      }
    });
  });
  const sql = `select * from wallpapers where downloadImageUrl like '%.jpg%' or downloadImageUrl like '%.JPG%' or 
  downloadImageUrl like '%.png%' or downloadImageUrl like '%.PNG%' order by updated_at desc limit ?,?`;
  const offset = (Number(req.query.pageIndex) - 1) * Number(req.query.pageSize);
  const count = Number(req.query.pageSize);
  db.query(sql, [offset, count], (err, results) => {
    if (err) {
      return res.send({
        flag: 500,
        msg: err.message,
      });
    } else {
      return res.send({
        flag: 1,
        msg: "success",
        data: {
          list: results.map((item) => resultsWithCamelCase(item)),
          total: totalCount,
        },
      });
    }
  });
};

exports.dataListByCateId = async (req, res) => {
  const countSql = `select count(*) as count from wallpapers where category_id=?`;
  const totalCount = await new Promise((resolve, reject) => {
    db.query(countSql, [req.query.cateId], (err, results) => {
      if (err) {
        return res.send({
          flag: 500,
          msg: err.message,
        });
      } else {
        resolve(results[0].count);
      }
    });
  });
  const sql = `select * from wallpapers where category_id=? order by updated_at desc limit ?,?`;
  const offset = (Number(req.query.pageIndex) - 1) * Number(req.query.pageSize);
  const count = Number(req.query.pageSize);
  db.query(sql, [req.query.cateId, offset, count], (err, results) => {
    if (err) {
      return res.send({
        flag: 500,
        msg: err.message,
      });
    } else {
      return res.send({
        flag: 1,
        msg: "success",
        data: {
          list: results.map((item) => resultsWithCamelCase(item)),
          total: totalCount,
        },
      });
    }
  });
};

exports.imageDetail = async (req, res) => {
  const sql = `select * from wallpapers where imageCode=?`;
  db.query(sql, [req.params.imageCode], (err, results) => {
    if (err) {
      return res.send({
        flag: 500,
        msg: err.message,
      });
    } else {
      return res.send({
        flag: 1,
        msg: "success",
        data: {
          list: results.map((item) => resultsWithCamelCase(item)),
          total: results.length,
        },
      });
    }
  });
};

exports.entryPassword = async (req, res) => {
  return res.send({
    flag: 1,
    msg: "success",
    data: "masterh",
  });
};

exports.addCount = async (req, res) => {
  const result = await getWXUserInfoByCode(req.body.appid, req.body.wxcode);
  if (result && result.flag != 1) {
    // 为了防止接口被过度使用，必须在微信小程序环境下使用
    return res.send({
      flag: 500,
      msg: result.msg,
    });
  }
  const result2 = await getUserById(req.body.userId);
  if (result2) {
    const result3 = JSON.stringify(result2);
    const jsonObj = JSON.parse(result3);
    const updateTime = moment(new Date())
      .utcOffset(8)
      .format("YYYY-MM-DD HH:mm:ss");
    const sql =
      "update users set can_problem_count=?, total_problem_count=?, update_time=? where id=?";
    db.query(
      sql,
      [
        jsonObj.can_problem_count + 5,
        jsonObj.total_problem_count + 5,
        updateTime,
        req.body.userId,
      ],
      (err, results) => {
        if (err) {
          return res.send({
            flag: 500,
            msg: err.message,
          });
        }
        return res.send({
          flag: 1,
          msg: "更新成功",
        });
      }
    );
  } else {
    return res.send({
      flag: 500,
      msg: "更新失败",
    });
  }
};

/**
 * 通过openid获取用户信息
 * @param {*} req 
 * @param {*} res 
 */
exports.getUserInfo = async (req, res) => {

};

/**
 * 壁纸小程序传code换取openid
 * @param {*} req 
 * @param {*} res 
 */
exports.code2session = async (req, res) => {
  
}
